<?php

namespace app\model;

use think\Model;
use app\service\EncryptionService;

class Account extends Model
{
    // 表名
    protected $name = 'accounts';

    // 自动时间戳
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';

    // 字段类型转换
    protected $type = [
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'last_used_at' => 'datetime',
        'expires_at' => 'datetime',
        'is_favorite' => 'boolean',
    ];

    // 关联用户
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    // 关联分类
    public function category()
    {
        return $this->belongsTo(Category::class, 'category_id', 'id');
    }

    // 获取用户账号列表
    public static function getUserAccounts($userId, $categoryId = null, $keyword = null, $isFavorite = null)
    {
        $query = self::where('user_id', $userId);

        if ($categoryId) {
            $query->where('category_id', $categoryId);
        }

        if ($keyword) {
            $query->where(function ($query) use ($keyword) {
                $query->where('title', 'like', '%' . $keyword . '%')
                    ->whereOr('website', 'like', '%' . $keyword . '%')
                    ->whereOr('tags', 'like', '%' . $keyword . '%');
            });
        }

        if ($isFavorite !== null) {
            $query->where('is_favorite', $isFavorite);
        }

        return $query->with(['category'])
            ->order('is_favorite', 'desc')
            ->order('last_used_at', 'desc')
            ->order('updated_at', 'desc')
            ->select();
    }

    // 获取收藏账号
    public static function getFavoriteAccounts($userId)
    {
        return self::where('user_id', $userId)
            ->where('is_favorite', 1)
            ->with(['category'])
            ->order('last_used_at', 'desc')
            ->order('updated_at', 'desc')
            ->select();
    }

    // 搜索账号
    public static function searchAccounts($userId, $keyword)
    {
        return self::where('user_id', $userId)
            ->where(function ($query) use ($keyword) {
                $query->where('title', 'like', '%' . $keyword . '%')
                    ->whereOr('website', 'like', '%' . $keyword . '%')
                    ->whereOr('tags', 'like', '%' . $keyword . '%');
            })
            ->with(['category'])
            ->order('is_favorite', 'desc')
            ->order('last_used_at', 'desc')
            ->select();
    }

    // 更新最后使用时间
    public function updateLastUsed()
    {
        $this->last_used_at = date('Y-m-d H:i:s');
        return $this->save();
    }

    // 切换收藏状态
    public function toggleFavorite()
    {
        $this->is_favorite = !$this->is_favorite;
        return $this->save();
    }

    // 检查密码是否过期
    public function isPasswordExpired()
    {
        if (!$this->expires_at) {
            return false;
        }
        return strtotime($this->expires_at) <= time();
    }

    // 获取即将过期的账号
    public static function getExpiringAccounts($userId, $days = 7)
    {
        $cutoffTime = date('Y-m-d H:i:s', time() + $days * 24 * 3600);
        return self::where('user_id', $userId)
            ->where('expires_at', '<=', $cutoffTime)
            ->where('expires_at', '>', date('Y-m-d H:i:s'))
            ->with(['category'])
            ->order('expires_at', 'asc')
            ->select();
    }

    // 获取已过期的账号
    public static function getExpiredAccounts($userId)
    {
        return self::where('user_id', $userId)
            ->where('expires_at', '<=', date('Y-m-d H:i:s'))
            ->with(['category'])
            ->order('expires_at', 'desc')
            ->select();
    }

    // 获取标签数组
    public function getTagsArrayAttr()
    {
        return $this->tags ? explode(',', $this->tags) : [];
    }

    // 设置标签
    public function setTagsArrayAttr($value)
    {
        $this->tags = is_array($value) ? implode(',', $value) : $value;
    }

    // 获取加密方式信息
    public function getEncryptMethodInfoAttr()
    {
        return [
            'method' => $this->encrypt_method ?: 'AES-256-GCM',
            'version' => $this->encrypt_version ?: '1.0'
        ];
    }

    // 获取解密后的用户名
    public function getUsernameAttr()
    {
        if (empty($this->username_encrypted)) {
            return '';
        }

        try {
            $method = $this->encrypt_method ?: 'AES-256-GCM';
            return EncryptionService::decrypt($this->username_encrypted, $method);
        } catch (\Exception $e) {
            // 如果解密失败，可能是明文数据，直接返回
            return $this->username_encrypted;
        }
    }

    // 获取解密后的密码
    public function getPasswordAttr()
    {
        if (empty($this->password_encrypted)) {
            return '';
        }

        try {
            $method = $this->encrypt_method ?: 'AES-256-GCM';
            return EncryptionService::decrypt($this->password_encrypted, $method);
        } catch (\Exception $e) {
            // 如果解密失败，可能是明文数据，直接返回
            return $this->password_encrypted;
        }
    }

    // 获取解密后的备注
    public function getNotesAttr()
    {
        if (empty($this->notes_encrypted)) {
            return '';
        }

        try {
            $method = $this->encrypt_method ?: 'AES-256-GCM';
            return EncryptionService::decrypt($this->notes_encrypted, $method);
        } catch (\Exception $e) {
            // 如果解密失败，可能是明文数据，直接返回
            return $this->notes_encrypted;
        }
    }

    // 获取域名（从网址中提取）
    public function getDomainAttr()
    {
        if (!$this->website) {
            return '';
        }

        $url = $this->website;
        if (!preg_match('/^https?:\/\//', $url)) {
            $url = 'http://' . $url;
        }

        $parsed = parse_url($url);
        return $parsed['host'] ?? '';
    }

    // 统计用户账号数据
    public static function getUserAccountStats($userId)
    {
        $total = self::where('user_id', $userId)->count();
        $favorite = self::where('user_id', $userId)->where('is_favorite', 1)->count();
        $expired = self::where('user_id', $userId)
            ->where('expires_at', '<=', date('Y-m-d H:i:s'))
            ->count();
        $expiring = self::where('user_id', $userId)
            ->where('expires_at', '<=', date('Y-m-d H:i:s', time() + 7 * 24 * 3600))
            ->where('expires_at', '>', date('Y-m-d H:i:s'))
            ->count();

        // 统计分类数量（包括用户创建的分类和已使用的分类）
        $categoryCount = Category::where('user_id', $userId)->count();

        return [
            'totalAccounts' => $total,
            'favoriteAccounts' => $favorite,
            'expiredAccounts' => $expired,
            'expiringAccounts' => $expiring,
            'totalCategories' => $categoryCount,
        ];
    }
}